var RNFS = require('react-native-fs');
import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    StyleSheet,
    Dimensions,
    TouchableWithoutFeedback,
    TouchableOpacity
} from 'react-native';
import Video from 'react-native-video';//播放视频插件。自动link【settings.gradle，MainApplication.java，app/build.gradle】：react-native link react-native-orientation-locker
import store from '../../../store/configureStore'
// import ScreenOrientation, { PORTRAIT, LANDSCAPE } from "react-native-orientation-locker/ScreenOrientation";
import Orientation from 'react-native-orientation-locker';//全屏
import Slider from '@react-native-community/slider';//进度条
import { Videos, videopath, userpath } from '../../../utils/path'

let screenWidth = Dimensions.get('window').width;//获取分辨率
let screenHeight = Dimensions.get('window').height;
console.log(screenWidth + "   " + screenHeight + "带有小数");
export default class TaskPage extends Component {
    static navigationOptions = {
        headerShown: false,
        tabBarLabel: '好友',
        tabBarIcon: ({ focused }) => {
            if (focused) {
                return (
                    <Text>这是好友</Text>

                    // <Image style={styles.tabBarIcon} source={require('../../img/fri_sel.png')}/>
                );
            }
            return (
                <Text>这是好友</Text>

                // <Image style={styles.tabBarIcon} source={require('../../img/fri_nor.png')}/>
            );
        },
    };
    constructor(props) {
        // console.log(store.getState(), props)
        // 监听store的数据更新，可以注销更新，unsubscriobe.
        super(props);
        this.changePausedState = this.changePausedState.bind(this);
        this.customerSliderValue = this.customerSliderValue.bind(this);
        this.enterFullScreen = this.enterFullScreen.bind(this);
        this._changePauseSliderFullState = this._changePauseSliderFullState.bind(this);
        this._onStartShouldSetResponder = this._onStartShouldSetResponder.bind(this);
        this.state = {
            ...store.getState(),
            isPlay: 1,
            duration: 0,
            currentTime: "",
            paused: "",
            sliderValue: 0,   //进度条的进度 
            isPaused: false,  //是暂停
            //用来控制进入全屏的属性
            videoWidth: screenWidth,
            videoHeight: screenHeight,
            isFullScreen: false,
            isVisiblePausedSliderFullScreen: false,
            videos: [],
            path: "",
            nowindex: 0
        }
    }


    // 视频播放存在的方法



    onEnd = () => {
        var path = this.props.navigation.state.params
        if (path) {
            this.setState({ isPaused: true });  //暂停不在播放
            // 搜寻到以秒为单位的指定位置。秒是一个浮点值。  
            this.player.seek(0)//画面在某个时间点

        } else {
            if (this.state.nowindex < this.state.videos.length - 1) {
                this.setState({ nowindex: this.state.nowindex + 1, path: this.state.videos[this.state.nowindex + 1].path })
            } else {
                this.setState({ nowindex: 0, path: this.state.videos[0].path })
            }
            this.setState({ isPaused: false });  //播放
            this.player.seek(0)//画面在某个时间点
            // 搜寻到以秒为单位的指定位置。秒是一个浮点值。  
        }
        console.log(this.state.path)
    };

    onAudioBecomingNoisy = () => {
        this.setState({ paused: true })
    };

    onAudioFocusChanged = ({ event: { hasAudioFocus: boolean } }) => {
        this.setState({ paused: !event.hasAudioFocus })
    };






    changePausedState() { //控制按钮显示播放，要显示进度条3秒钟，之后关闭显示
        this.setState({
            isPaused: this.state.isPaused ? false : true,
            isVisiblePausedSliderFullScreen: true
        })
        //这个定时调用失去了this指向
        let that = this;
        setTimeout(function () {
            that.setState({
                isVisiblePausedSliderFullScreen: false
            })
        }, 3000)
    }
    _changePauseSliderFullState() { // 单击事件，是否显示 “暂停、进度条、全屏按钮 盒子”
        let flag = this.state.isVisiblePausedSliderFullScreen ? false : true;
        this.setState({
            isVisiblePausedSliderFullScreen: flag,
            isPaused: this.state.isPaused ? false : true,

        })
        this.props.navigation.replace('Home')  
        //这个定时调用失去了this指向
        let that = this;
        setTimeout(function () {
            that.setState({
                isVisiblePausedSliderFullScreen: false
            })
        }, 3000)
    }
    //格式化音乐播放的时间为0：00。借助onProgress的定时器调用，更新当前时间
    formatMediaTime(time) {
        let minute = Math.floor(time / 60);
        let second = parseInt(time - minute * 60);
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return minute + ":" + second;

    }
    //加载视频调用，主要是拿到 “总时间”，并格式化
    customerOnload(e) {
        let time = e.duration;
        this.setState({
            duration: time
        })
    }
    // 获得当前的，播放时间数，但这个数是0.104，需要处理
    customerOnprogress(e) {
        let time = e.currentTime;   // 获取播放视频的秒数       
        this.setState({
            currentTime: time,
            sliderValue: time
        })
    }
    // 移动滑块，改变视频播放进度，注意滑块UI时间和视频进度虽然的分离的，但是逻辑上是同步的
    customerSliderValue(value) {
        this.player.seek(value);
    }
    enterFullScreen() { //1.改变宽高  2.允许进入全屏模式  3.如何配置屏幕旋转,不需要改变进度条盒子的显示和隐藏
        this.setState({
            videoWidth: screenWidth,
            videoHeight: screenHeight,
            isFullScreen: true,
        })
        // 直接设置横屏方向
        Orientation.lockToLandscape();
    }
    _onStartShouldSetResponder(e) {
        console.log(e);
    }
    turnback() {
        console.log(1111111, this)
        // this.props.navigation.navigate('Home')
    }
    RandomNumBoth(arr, maxNum) {
        // 函数把this.state,slicearr的值用arr变量接收了，所以这里面对arr操作不会影响到state的值
        var numArr = [];
        var arrLength = arr.length;
        for (var i = 0; i < arrLength; i++) {
            var Rand = arr.length;
            //取出随机数 
            var number = Math.floor(Math.random() * arr.length); //生成随机数num是存在的某个索引值
            console.log(number, Math.random())
            numArr.push(arr[number]); //往新建的数组里面传入数值
            arr.splice(number, 1); //传入一个删除一个原数组的对应索引，改变原数组arr,避免重复，被删除的放在新的数组，
            if (arr.length <= arrLength - maxNum) {
                return numArr;
            }
        }
    }
    componentDidMount() {
        var initial = Orientation.getInitialOrientation();
        var path = this.props.navigation.state.params
        console.log(path)
        if (!path) {
            // 读取视频文件夹，是循环播放还是随机播放
            // 读取库里的特定路径的视频资源
            RNFS.readDir(Videos) // On Android, use "RNFS.DocumentDirectoryPath（内置存储）" (MainBundlePath is not defined)
                .then((result) => {
                    console.log('GOT RESULT', result);
                    this.setState({ videos: result, path: result[0].path  })
                    //  /0.顺序，1随机
                    if (this.state.user[0]['issort'] == 1) {
                        result = this.RandomNumBoth(result, result.length)
                        this.setState({ videos: result, path: result[0].path })

                    }
                    console.log(this.state.user[0], 'hhhhhhhhhhhhh')

                    // stat the first file
                })
        } else {
            this.setState({ path: path.path })
        }

        if (initial === 'PORTRAIT') {
            console.log('是竖屏将他横屏过来');
            Orientation.lockToLandscape();

        } else {
            console.log('如果是横屏，就将其旋转过来lockToPortrait是竖屏，lockToLandscape是横屏');
            Orientation.lockToLandscape();
        }
    }
     /// 屏幕旋转时宽高会发生变化，可以在onLayout的方法中做处理，比监听屏幕旋转更加及时获取宽高变化
  onLayout = event => {
    //获取根View的宽高
    let { width, height } = event.nativeEvent.layout;
    console.log("通过onLayout得到的宽度：" + width);
    console.log("通过onLayout得到的高度：" + height);

    // 一般设备横屏下都是宽大于高，这里可以用这个来判断横竖屏
    let isLandscape = width > height;
    if (isLandscape) {
      this.setState({
        videoWidth: width,
        videoHeight: height,
        isFullScreen: true
      });
    } else {
      this.setState({
        videoWidth: width,
        videoHeight: (width * 9) / 16,
        isFullScreen: false
      });
    }
    // Orientation.unlockAllOrientations();
  };
  componentWillMount() {
    Orientation.lockToLandscape();
}

    render() {
        const { navigate,push,replace } = this.props.navigation;

        let playButtonComponent = (
            <TouchableWithoutFeedback
                onPress={this.changePausedState}
            >
                <View style={styles.playBtn}>
                </View>
            </TouchableWithoutFeedback>
        );
        let pausedBtn = this.state.isPaused ? playButtonComponent : null;
        // 暂停按钮、进度条、全屏按钮 是否显示
        let pausedSliderFullComponent = (
            <View style={{ position: "absolute", bottom: 15 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    {/* 进度条按钮     */}
                    <View style={styles.sliderBox}>
                        <Text>{this.formatMediaTime(this.state.currentTime)}</Text>
                        <Slider
                            style={{ width: 200, height: 40 }}
                            value={this.state.sliderValue}
                            maximumValue={this.state.duration}
                            thumbTintColor="#fff" //开关夹点的yanse              
                            minimumTrackTintColor="red"
                            maximumTrackTintColor="#ccc"
                            step={1}
                            onValueChange={this.customerSliderValue}
                        />
                        <Text>{this.formatMediaTime(this.state.duration)}</Text>
                    </View>
                    {/* 全屏按钮 */}
                    <View>
                        <TouchableOpacity
                            // onPress={this.enterFullScreen}
                            onPress={() => {
                                replace('Home', { user: 'Sybil' })
                            }}
                        >
                            <Text style={{ backgroundColor: 'black', padding: 3, opacity: 0.5, marginLeft: 10, borderRadius: 8, color: '#fff' }}>退出</Text>
                        </TouchableOpacity>
                    </View>


                </View>
            </View>
        );
        let pausedSliderFull = this.state.isVisiblePausedSliderFullScreen ? pausedSliderFullComponent : null;
        return (
            <View style={styles.container} onLayout={this.onLayout}>
                <TouchableWithoutFeedback
                    onPress={this._changePauseSliderFullState}
                    onResponderMove={this._onStartShouldSetResponder}
                >
                    <Video
                        ref={(ref) => {
                            this.player = ref
                        }}
                        // https://www.npmjs.com/package/react-native-video#source
                        // source={ require( '../../../../../assets/imgs/video.mp4')}   // Can be a URL or a local file.
                        source={{ uri: `file:///${this.state.path}` }}   // Can be a URL or a local file.
                        // poster='https://baconmockup.com/300/200/'
                        // poster='file:///storage/emulated/0/Download/timg.jpg'
                        // posterResizeMode='stretch'
                        resizeMode="cover"           // 视频的自适应伸缩铺放行为，contain、stretch、cover
                        style={{ width: this.state.videoWidth, height: this.state.videoHeight }}
                        repeat={false}                // 是否重复播放
                        rate={this.state.isPlay ? 1 : 0}   // 控制播放速率，0 代表不播放暂停, 1代表正常速度播放normal.
                        paused={this.state.isPaused}     // true代表暂停，默认为false
                        onLoad={(e) => this.customerOnload(e)}//加载媒体并准备播放时调用的回调函数。
                        onProgress={(e) => this.customerOnprogress(e)}//视频播放过程中每个间隔进度单位调用的回调函数
                        onEnd={this.onEnd}//视频播放结束时的回调函数
                        onAudioBecomingNoisy={this.onAudioBecomingNoisy}//音频变得嘈杂时的回调 - 应暂停视频
                        onAudioFocusChanged={this.onAudioFocusChanged}//音频焦点丢失时的回调 - 如果焦点丢失则暂停
                        fullscreen={this.state.isFullScreen}

                    />
                </TouchableWithoutFeedback>
                <View style={{ backgroundColor: "black", opacity: 0.5, position: "absolute", bottom: 0, width: '100%', height: 30, justifyContent: "center" }}><Text style={{ textAlign: "center", color: "#fff", fontWeight: 'bold' }} onPress={() => {
                this.props.navigation.replace('Home')}}>点击任意位置开始答题评测！</Text></View>
                {/* 播放的按钮：点击之后需要消失 */}
                {/* {pausedBtn} */}
                {/* 暂停按钮，进度条，全屏按钮 */}
                {/* {pausedSliderFull} */}
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabBarIcon: {
        width: 21,
        height: 21,
    },
    myVideo: {
        width: 340,
        height: 240
    },
    playBtn: {
        width: 50,
        height: 50,
        backgroundColor: 'red',
        borderRadius: 50,
        position: "absolute",
        top: "50%",
        left: "50%",
        marginLeft: -25,
        marginTop: -25,
        zIndex: 999
    },
    sliderBox: {
        flex: 0,
        flexDirection: 'row',
        alignItems: 'center'
    }
});